package com.lzx.controller;

import com.lzx.model.User;
import com.lzx.service.UserService;
import com.lzx.utils.SessionUtil;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;

@Controller
@RequestMapping("")
public class loginController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public String login() {
        //model.addAttribute("list", list);
        return "system/login";
    }

    @RequestMapping("/logindo")
    public String logindo(Model model, HttpServletRequest request) {
        String info = "";
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = null;
        try {
            user = userService.queryByUserName(username);
        } catch (SQLException e) {
            e.printStackTrace();
            info = "尝试连接数据库失败";
        }
        if (user == null) {
            info = "未找到当前用户";
        }
        if (user != null) {
            String md5 = new SimpleHash("MD5", password, username, 1).toString();
            System.out.println(user.getPassword());
            System.out.println(md5);
            if (!user.getPassword().equals(md5)) {
                info = "密码错误";
            }
        }
        if (info.equals("")) {
            SessionUtil.setUser(request, user);
            if(username.equals("system")){
                return "redirect:index/index";
            }else{
                return "redirect:nydsj/nydsj.html";
            }

        } else {
            model.addAttribute("username", username);
            model.addAttribute("password", password);
            model.addAttribute("info", info);
            return "system/login";
        }
    }
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request) {
        SessionUtil.removeUser(request);
        return "system/login";
    }


}
